# -*- coding:utf-8 -*-
# @Time  : 2019/12/3 18:55
# @Author: wangxb
'''
# 根据本地指定路径下的apk进行解析微信ID
## 1、使用unzip解压jar包，解压.class文件到指定目录
## 2、使用jad反编译指定目录下的.class文件
'''
import datetime
import os
import subprocess
import time

from classes.jarOperation import generateJarFile, getAllClassesFileInAPK, changeFileSuffix, copyAPKToZip
from classes.searchContent import examineDirectory, FindConetent, traverseDocument

# apk包名
# apk_name = 'com.tencent.mm.apk'
# 不需要解析的app数组
appList = ["奇热漫画", "大角虫漫画", "樊登读书", "网易漫画", "酷听听书", "翻阅小说", "ONE·一个", "当当云阅读", "免费小说全集", "漫漫漫画", "潇湘书院小说阅读", "新漫画",
           "触漫", "咚漫", "鲸鱼阅读软件"]
# 项目的根路径
root_path = os.path.dirname(os.getcwd())
# apk文件路径
apk_file_path = root_path + os.sep + 'APKSources' + os.sep
# apk的zip文件路径
# apk_zip_file_path = ''
# 反编译后的zip文件路径
jar_zip_file_path = root_path + os.sep + 'zipSources'
# jadx工具所在路径
jadx_tools_path = root_path + os.sep + 'jadx-1.1.0' + os.sep + 'bin'
# jadx反编译后文件的路径（resources/:class文件目录，sources/：java文件目录）
jadxOutputPath = root_path + os.sep + 'JadxCatalog'
javaRootPath = jadxOutputPath + os.sep + 'sources'
# 搜索结果输出路径
outputPath = root_path + os.sep + 'output_files_jadx.txt'


def totalProcess(apk_file_path):
    try:
        print('\n#############################清理jadx输出文件目录#############################')
        # 删除之前搜索目录中遗留的文件
        examineDirectory(jadxOutputPath)

        print(
            '\n#############################Start decompile ' + apk_file_path + '#############################')
        # 调用jadx反编译apk包
        p = subprocess.Popen(jadx_tools_path[
                             0:1] + ": && cd " + jadx_tools_path + " && jadx -d %s %s" % (
                                 jadxOutputPath, apk_file_path),
                             shell=True)
        # shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        result = p.wait()
        if result != 0:
            print("####################### unzip解压jar包出错 #######################")
        time.sleep(1)

        # 根据关键字搜索.java文件路径下所有文件的内容
        findObj = FindConetent(javaRootPath)
        findObj.find_file(findObj)
        findObj.walk(findObj, outputPath, apk_file_path)

    except BaseException as errors:
        print(errors)
    finally:
        # 删除之前搜索目录中遗留的文件
        examineDirectory(jadxOutputPath)


if __name__ == '__main__':

    start = datetime.datetime.now()
    # 获取本地制定路径下所有apk对象
    apkNameList = traverseDocument(apk_file_path)

    # 对数组中的apk进行解析
    for pkgName in apkNameList:

        try:
            # 在输出文件中区分每个app的微信ID
            f = open(outputPath, "a", encoding='utf-8')
            f.write('\n#############################Start An APP : %s ##################################\n' % pkgName)
            f.close()
            apk_file_path_final = apk_file_path + pkgName
            # 获取apk后，进行后续的jadx反编译，以及搜索微信ID
            totalProcess(apk_file_path_final)
            f = open(outputPath, "a", encoding='utf-8')
            f.write('#############################End An APP : %s ##################################\n' % pkgName)
            f.close()
        except BaseException as error:
            print(error)
        # finally:
        #     f.close()
    end = datetime.datetime.now()
    print('Running time: %s Seconds' % (end - start))
